package controller;

import java.util.List;
import java.awt.Point;
import java.util.ArrayList;
import java.util.Map;

import utils.PlayerSides;
import utils.RandomGenerator;

import model.Board;
import model.pieces.Piece;

/**
 * Class implements a player managed by computer. Pieces and moves are chosen randomly, but moves that treat
 * the friendly King are not chosen
 */
public class ComputerPlayer extends Player{

	private static final int DELAY = 1000; // delay in computer player response
	private GameManager gameManager; // manages game
	
	public ComputerPlayer(PlayerSides.Sides side, Map<Point, Piece> pieces, Board board, GameManager gameManager) {
		
		// use base class constructor
		super(side, pieces, board);
		
		// set members according to given values
		this.gameManager = gameManager;
	}
	
	/**
	 * Randomly chooses a piece.
	 * If piece has at least one safe move, a safe move is chosen randomly, and move is returned.
	 * If chosen piece does not have a safe move, another piece is chosen
	 */
	public Movement chooseMove() {
		
		// get player's piece positions
		List<Point> piecePositions = new ArrayList<Point>(pieces.keySet());
		
		// indicates if has chosen a move
		boolean movementIsSet = false;
		
		// move's source and destination
		Point source = null, dest = null;
		
		// find a piece that can move at current turn
		while (!movementIsSet) {
			
			// choose random piece
			source = piecePositions.get(RandomGenerator.nextInt(piecePositions.size()));
			
			// get its safe destinations
			List<Point> destinations = gameManager.getSafeDestinations(source);
			
			// check if can move
			if (destinations.isEmpty()) {
				
				// cannot move, keep searching
				continue;
			}
			
			// randomly choose where to move
			dest = destinations.get(RandomGenerator.nextInt(destinations.size()));			
			
			// done searching
			movementIsSet = true;
		}
		
		// delay the player response
		try {
			Thread.sleep(DELAY);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		// return chosen move
		return new Movement(source, dest);
	}

	/**
	 * Returns default choice for piece to replace Pawn
	 */
	@Override
	public int getReplacingPawnOption(String[] options, int defaultOption) {
		return defaultOption;
	}
}